package com.wqj.ride.happyriding.nav.activity

import android.app.PendingIntent.getActivity
import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_offline_map.*
import android.widget.TextView
import android.support.v7.widget.RecyclerView.ViewHolder
import android.view.LayoutInflater
import android.view.ViewGroup
import android.support.v7.widget.RecyclerView
import android.view.View
import org.jetbrains.anko.ctx
import android.content.res.TypedArray
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.util.Log
import android.widget.ImageView
import com.amap.api.maps.offlinemap.OfflineMapCity
import com.amap.api.maps.offlinemap.OfflineMapManager
import com.amap.api.maps.offlinemap.OfflineMapProvince
import android.widget.Toast
import android.content.DialogInterface
import android.media.Image
import android.support.v7.app.AlertDialog
import android.view.Gravity
import com.iflytek.cloud.resource.Resource.setTitle
import com.wqj.ride.happyriding.R

class OfflineMapActivity : AppCompatActivity(), OfflineMapManager.OfflineMapDownloadListener {

    private var offlineMapDataList: ArrayList<OfflineMapData> = ArrayList()
    lateinit var amapManager: OfflineMapManager

    data class OfflineMapData(var name: String, var size: Long, var children: ArrayList<OfflineMapData>?)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_offline_map)
        amapManager = OfflineMapManager(this, this)
        initOfflineMapProvinceList()
        //设置布局管理器
        recyclerview.setLayoutManager(LinearLayoutManager(this))
        //设置adapter
        var mAdapter = HomeAdapter()
        recyclerview.setAdapter(mAdapter)
        //设置Item增加、移除动画
        recyclerview.setItemAnimator(DefaultItemAnimator())
        //添加分割线
        recyclerview.addItemDecoration(DividerItemDecoration(
                ctx, VERTICAL_LIST))
    }

    protected fun initOfflineMapProvinceList() {

        var provinceList = amapManager.getOfflineMapProvinceList()

        var i: Int = 0
        while (i<provinceList.size) {
            if (provinceList[i].cityList.size > 1) {
                var list = ArrayList<OfflineMapData>()
                var mapData = OfflineMapData("1", 0, null)
                mapData.name = provinceList[i].provinceName
                mapData.size = provinceList[i].size
                provinceList[i].cityList.forEach{
                    var mapData = OfflineMapData("1", 0, null)
                    mapData.name = it.city
                    mapData.size = it.size
                    list.add(mapData)
                }
                mapData.children = list
                offlineMapDataList.add(mapData)
            } else {
                var mapData = OfflineMapData("1", 0, null)
                mapData.name = provinceList[i].provinceName
                mapData.size = provinceList[i].size
                mapData.children = ArrayList<OfflineMapData>()
                offlineMapDataList.add(mapData)
            }
            i++
        }
    }

    internal inner class HomeAdapter : RecyclerView.Adapter<HomeAdapter.MyViewHolder>() {
        val VIEW_TYPE_CITY: Int = 0
        val VIEW_TYPE_PROV: Int = 1

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
            when (viewType) {
                VIEW_TYPE_CITY -> {
                    return MyViewHolder(LayoutInflater.from(
                            this@OfflineMapActivity).inflate(R.layout.offline_map_item_city, parent,
                            false))
                }
                VIEW_TYPE_PROV -> {
                    return MyViewHolder(LayoutInflater.from(
                            this@OfflineMapActivity).inflate(R.layout.offline_map_item_prov, parent,
                            false))
                }
                else -> {
                    return MyViewHolder(LayoutInflater.from(
                            this@OfflineMapActivity).inflate(R.layout.offline_map_item_prov, parent,
                            false))
                }
            }

        }

        override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
            var size = (offlineMapDataList[position].size / 1024 / 1024).toString()
            holder.zoneName.text = offlineMapDataList[position].name
            holder.mapSize.text = "地图" + size + "MB"

            holder.item.setOnClickListener {v ->
                Log.d("wqj", "item clicked: " + position)
                if (holder.isExpanded) {
                    if (offlineMapDataList[position].children != null && offlineMapDataList[position].children!!.size > 1) {
                        offlineMapDataList.removeAll(offlineMapDataList[position].children as Collection<OfflineMapData>)
                        notifyItemRangeRemoved(position + 1, offlineMapDataList[position].children!!.size)
                        notifyItemRangeChanged(0, getItemCount(), "change_position")
                        holder.isExpanded = false
                        holder.arrowView.setImageResource(R.drawable.rightarrow)
                    }
                } else {
                    if (offlineMapDataList[position].children != null && offlineMapDataList[position].children!!.size > 1) {
                        offlineMapDataList.addAll(position + 1, offlineMapDataList[position].children as Collection<OfflineMapData>)
                        notifyItemRangeChanged(position + 1, offlineMapDataList[position].children!!.size)
                        notifyItemRangeChanged(0, getItemCount(), "change_position")
                        holder.isExpanded = true
                        holder.arrowView.setImageResource(R.drawable.downarrow)
                    }
                }
            }

            holder.downloadView.setOnClickListener {v ->
                var title = TextView(ctx)
                title.setText("下载地图")
                title.setPadding(10, 30, 10, 10)
                title.gravity = Gravity.CENTER_HORIZONTAL
                title.setTextSize(23f)

                var msg = TextView(ctx)
                msg.setText("" + holder.zoneName.text + "(" + size + "MB)")
                msg.setPadding(10, 5, 10, 5)
                msg.setGravity(Gravity.CENTER_HORIZONTAL)
                msg.setTextSize(16f)

                val builder = AlertDialog.Builder(ctx)
                builder.setCustomTitle(title)//设置标题
                builder.setIcon(R.drawable.ic_launcher)//设置图标
                builder.setView(msg)//设置内容
                /*添加对话框中确定按钮和点击事件*/
                builder.setPositiveButton("确定", DialogInterface.OnClickListener { arg0, arg1 ->
                    Toast.makeText(ctx, "开始下载", Toast.LENGTH_SHORT).show()
                    // amapManager.downloadByCityName(holder.zoneName.toString())
                })
                /*添加对话框中取消按钮和点击事件*/
                builder.setNegativeButton("取消", DialogInterface.OnClickListener { arg0, arg1 ->
                    // Toast.makeText(ctx, "点击了取消按钮", Toast.LENGTH_SHORT).show()
                })
                val dialog = builder.create()//获取dialog
                dialog.show()//显示对话框

            }
        }

        override fun getItemViewType(position: Int): Int {
            if (offlineMapDataList[position].children == null) {
                return VIEW_TYPE_CITY
            } else {
                return VIEW_TYPE_PROV
            }
        }

        override fun getItemCount(): Int {
            return offlineMapDataList.size
        }

        internal inner class MyViewHolder(view: View) : ViewHolder(view) {

            var item: View
            var zoneName: TextView
            var mapSize: TextView
            var navSize: TextView
            var downloadView: ImageView
            var arrowView: ImageView
            var isExpanded: Boolean = false

            init {
                item = view

                zoneName = view.findViewById<TextView>(R.id.zoneName)
                mapSize = view.findViewById<TextView>(R.id.mapSize)
                navSize = view.findViewById<TextView>(R.id.navSize)
                downloadView = view.findViewById<ImageView>(R.id.dldView)
                arrowView = view.findViewById<ImageView>(R.id.arrowView)
            }
        }
    }

    inner class DividerItemDecoration(context: Context, orientation: Int) : RecyclerView.ItemDecoration() {

        private val mDivider: Drawable?

        private var mOrientation: Int = 0

        init {
            val a = context.obtainStyledAttributes(ATTRS)
            mDivider = a.getDrawable(0)
            a.recycle()
            setOrientation(orientation)
        }

        fun setOrientation(orientation: Int) {
            if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) {
                throw IllegalArgumentException("invalid orientation")
            }
            mOrientation = orientation
        }

        override fun onDraw(c: Canvas, parent: RecyclerView) {
            Log.v("recyclerview", "onDraw()")

            if (mOrientation == VERTICAL_LIST) {
                drawVertical(c, parent)
            } else {
                drawHorizontal(c, parent)
            }
        }

        fun drawVertical(c: Canvas, parent: RecyclerView) {
            val left = parent.paddingLeft
            val right = parent.width - parent.paddingRight

            val childCount = parent.childCount
            for (i in 0 until childCount) {
                val child = parent.getChildAt(i)
                val v = android.support.v7.widget.RecyclerView(parent.context)
                val params = child
                        .layoutParams as RecyclerView.LayoutParams
                val top = child.bottom + params.bottomMargin
                val bottom = top + mDivider!!.intrinsicHeight
                mDivider.setBounds(left, top, right, bottom)
                mDivider.draw(c)
            }
        }

        fun drawHorizontal(c: Canvas, parent: RecyclerView) {
            val top = parent.paddingTop
            val bottom = parent.height - parent.paddingBottom

            val childCount = parent.childCount
            for (i in 0 until childCount) {
                val child = parent.getChildAt(i)
                val params = child
                        .layoutParams as RecyclerView.LayoutParams
                val left = child.right + params.rightMargin
                val right = left + mDivider!!.intrinsicHeight
                mDivider.setBounds(left, top, right, bottom)
                mDivider.draw(c)
            }
        }

        override fun getItemOffsets(outRect: Rect, itemPosition: Int, parent: RecyclerView) {
            if (mOrientation == VERTICAL_LIST) {
                outRect.set(0, 0, 0, mDivider!!.intrinsicHeight)
            } else {
                outRect.set(0, 0, mDivider!!.intrinsicWidth, 0)
            }
        }
    }

    override fun onDownload(p0: Int, p1: Int, p2: String?) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun onCheckUpdate(p0: Boolean, p1: String?) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun onRemove(p0: Boolean, p1: String?, p2: String?) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    companion object {

        private val ATTRS = intArrayOf(android.R.attr.listDivider)

        val HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL

        val VERTICAL_LIST = LinearLayoutManager.VERTICAL
    }
}
